﻿namespace NKernel.Core
{
    using System;

    using log4net;

    /// <summary>
    /// Singleton instance of the NKernel
    /// </summary>
    public sealed class NKernelSingleton
    {
        #region Fields

        private static readonly ILog Logger = LogManager.GetLogger(typeof (NKernelSingleton));
        private static readonly object SyncRoot = new Object();

        private readonly IKernel kernel;

        private static volatile NKernelSingleton instance;

        #endregion Fields

        #region Constructors

        private NKernelSingleton()
        {
            kernel = NKernelBuilder.Builder().MakeSynchronized().Build();

            KernelResult result = kernel.Manage();

            if (!result.Success)
            {
                Logger.ErrorFormat("Error encountered in managing the components: {0}", result.Message);
            }
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static NKernelSingleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (SyncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new NKernelSingleton();
                        }
                    }
                }

                return instance;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public IKernel Kernel
        {
            get
            {
                return kernel;
            }
        }

        #endregion Properties
    }
}